package cn.schoolwow.util.module.query.jsonarray.flow.filter;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.jsonobject.QueryJSONObject;
import cn.schoolwow.util.module.query.jsonarray.domain.JSONArrayQueryOption;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Collection;
import java.util.Set;

public class FilterJSONArrayByFieldValueInListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        JSONArrayQueryOption jsonQueryOption = flowContext.checkInstanceData(JSONArrayQueryOption.class);
        JSONArray filterArray = (JSONArray) flowContext.getData("filterArray");

        if(null==jsonQueryOption.fieldValueInListMap){
            return;
        }
        Set<Collection<String>> fieldNameSet = jsonQueryOption.fieldValueInListMap.keySet();
        filterArray.removeIf(instance->{
            JSONObject object = (JSONObject) instance;

            for(Collection<String> fieldNames:fieldNameSet){
                Object fieldValue = null;
                if(fieldNames.size()==1){
                    String fieldName = fieldNames.iterator().next();
                    fieldValue = object.get(fieldName);
                }else{
                    fieldValue = QueryJSONObject.newQuery(object)
                            .execute()
                            .getMultipleFieldValue(fieldNames);
                }
                Collection expectValueList = jsonQueryOption.fieldValueInListMap.get(fieldNames);
                if(!expectValueList.contains(fieldValue)){
                    return true;
                }
            }
            return false;
        });
    }

    @Override
    public String name() {
        return "过滤JSON数组-inQuery";
    }
}
